<?php

// 9/12/2009: immanuel192 write this action

// this action show all your current order in the shopping cart

if (!defined("EXPONENT")) exit("");
  // 10/10/2009: immanuel192 write this code to check permission of the submit form
  $md5_session='';
  if (isset($_POST['hidden_session']))  $md5_session=$_POST['hidden_session'];
  if (!($md5_session == md5(exponent_sessions_getTicketString())))
  {	
	exponent_flow_redirect();
  }
  else {
	// we continue check the empty user information 
	$username=''; $userphone=''; $useraddress=''; $useremail='';
	if (isset($_POST['name'])) $username=$_POST['name'];
	if (isset($_POST['phone'])) $userphone=$_POST['phone'];
	if (isset($_POST['address'])) $useraddress=$_POST['address'];
	if (isset($_POST['email'])) $useremail=$_POST['email'];
	
	// if this form contain wrong value
	if ($username == '' && $userphone == '' && $useraddress == '')
	{ exponent_flow_redirect(); return; } 
	
	global $user;
	global $db;
	$order_id=-1;
	$template = new template('storemodule','_checkout',$loc);
    // get all cache
    $ticket=exponent_sessions_getTicketString();
    $cache=$db->selectObjectsBySql("
       SELECT {$db->prefix}album.*,
              {$db->prefix}album_format.name as format_name,
              {$db->prefix}order_cache.* FROM {$db->prefix}order_cache INNER JOIN {$db->prefix}album ON {$db->prefix}order_cache.item_id = {$db->prefix}album.id INNER JOIN {$db->prefix}album_format ON {$db->prefix}album_format.id={$db->prefix}album.format WHERE ticket_string='{$ticket}'");
   // generate icon
    $total=0;
    foreach ($cache as $key=>$value){
      // get total
      if ($value->main_disk >0)
		$total+=$value->price*$value->main_disk;
	  if ($value->vocal >0)
		$total+=$value->price_vocal*$value->vocal;
	  if ($value->sheetbook >0)
		$total+=$value->price_sheet_book*$value->sheetbook;
	  if ($value->soundtrack >0)
		$total+=$value->price_soundtrack_disk*$value->soundtrack;
      // set icon
      if (strpos(strtolower($value->format_name),"dvd") >= 0)
        $value->icon="dvd";
      else if (strpos(strtolower($value->format_name),"cd") >= 0)
         $value->icon="cd";
      else
         $value->icon="music";
      
      if ($value->image_id == 0) {
		    $value->picpath = '';
     } else {
		      $file = $db->selectObject('file', 'id='.$value->image_id);
    		$value->picpath = $file->directory.'/'.$file->filename;
	     }
			
	     // for rating
    	$rate_1 = floor($value->rate);
	    $rate_half = $value->rate - $rate_1;
      $rate_2 = 5- $rate_1 - (($rate_half > 0)?1:0);
      $rate=array();
      for ($j=1;$j<=$rate_1;$j++)
        $rate[$j]=1; // for active rate
      if ($rate_half > 0)
        $rate[$rate_1+1]=3; // for rate half
      for ($j=5-$rate_2+1;$j<=5;$j++)
        $rate[$j]=2; // for active rate
      $value->rate=$rate;
	   // end of rating
			
	   // for format_type
	   $temp=$db->selectObject("album_format","id = ".$value->format);
	   $value->format_text = $temp->name;
	   // end of format type
	   // for genre 
      $temp=$db->selectObject("album_genre","id = ".$value->genre);
      $value->genre_text = $temp->name;
	   // end of genre   
     // count how many musics
     $musics=$db->countObjects('musics','album_id='.$value->id );
     $value->musics = $musics;
     
     // for location source
     $temp=unserialize($value->location_data);
     $value->src=$temp->src;
     
      $cache[$key]=$value;
    }
    
    // get ship fee
    //$is_logged=exponent_sessions_loggedIn();
    //if ($is_logged){
      $ship_fee=0;
    // // get user location
    // $country=strtolower($user->user_address->country);
    // if ($country == "usa" || $country == "canada")
    //  $ship_fee=0;
    // else
    //  $ship_fee=5;
    //} else {
      //$ship_fee=5;
    //}
    $template->assign("ship_fee",$ship_fee);
    
    $template->assign("orders",$cache);
    $template->assign("order_count",count($cache));
    // get language from album module and storemodule Default Views
    $more_lang=exponent_lang_loadFile("modules/albummodule/views/Default.php");
    $more_lang2=exponent_lang_loadFile("modules/storemodule/views/Default.php");
	$more_lang1=exponent_lang_loadFile("modules/storemodule/views/_view_cart.php");
    $more_lang3=exponent_lang_loadFile("modules/storemodule/step.php");
    $more_lang=array_merge($more_lang, $more_lang2, $more_lang3,$more_lang1);
    $template->assign("more_lang",$more_lang);
    $template->assign("is_logged",exponent_sessions_loggedIn());
		$perms = storemodule::permissions();
		$template->register_permissions(array_keys($perms),$loc);
		
		// before generate the output, we must clear all cache and make new bill
		$new_order=null;
		$new_order->ship_fee=$ship_fee;
		$new_order->total=$total + $ship_fee;
		$new_order->add_date=time();
		$new_order->state=2; // set waiting mode
		$new_order->name=$username;
		$new_order->address=$useraddress;
		$new_order->phone=$userphone;
		$new_order->email=$useremail;
    $new_order->note=$_REQUEST['note'];  
		$new_order_id=$db->insertObject($new_order,"orders");
		
		// order detail
		$order_detail=null;
		$order_detail->order_id=$new_order_id;
		foreach ($cache as $key=>$value)
		{
		  $order_detail->item_id=$value->id;
		  $order_detail->price=$value->price;
		  // 10/10/2009: immanuel add this code to fix error when user want to buy a part of the album
		  $order_detail->main_disk=$value->main_disk;
		  $order_detail->sheetbook=$value->sheetbook;
		  $order_detail->soundtrack=$value->soundtrack;
		  $order_detail->vocal=$value->vocal;
		  // for price
		  $order_detail->price=$value->price;
		  $order_detail->price_vocal=$value->price_vocal;
		  $order_detail->price_sheet=$value->price_sheet_book;
		  $order_detail->price_soundtrack=$value->price_soundtrack_disk;
		  // end
		  
		  $order_id=$db->insertObject($order_detail,"order_items");
		  // remove current item
		  $db->delete("order_cache","ticket_string = '{$ticket}' AND item_id={$value->id}");
		  // increase bought value of this album
		  $db->increment("album","bought",1,"id = {$value->id}");		  
    }
    // send email
    // 11/3/2009: immanuel192 add email 
	  // create email body message
    $e_template = new template('storemodule','_checkout_email',$loc);
    $e_template->assign('name',$new_order->name);
    $e_template->assign('address',$new_order->address);
	  $e_template->assign('phone',$new_order->phone);
	  $e_template->assign('email',$new_order->email);
	  $e_template->assign("orders",$cache);
	  $e_template->assign("order_id",$order_id);
	  $e_template->assign("add_date",date("d/m/Y"));
	  $e_template->assign("note", str_replace("\r\n","<br>",$_REQUEST['note']));
	    
	  $msg = $e_template->render();
    // send mail
    //if (!defined('SYS_SMTP')) require_once(BASE.'subsystems/smtp.php');
    //@exponent_smtp_mail($new_order->email,SITE_TITLE.' <'.SMTP_FROMADDRESS.'>',"Chi tiết đặt mua hàng tại " . SITE_TITLE . " ngày " .date("d/m/Y"),$msg);
    //@exponent_smtp_mail("trongtran47@gmail.com",SITE_TITLE.' <'.SMTP_FROMADDRESS.'>',"Chi tiết đặt mua hàng tại " . SITE_TITLE . " ngày " .date("d/m/Y"),$msg);
    require_once(BASE.'subsystems/mail.php');
    $emails=array();
    $emails[]=$new_order->email;
    $emails[]="trongtran47@gmail.com";
    $emails[]="trung@hpm.vn";
    $headers = array();
    $headers['From'] =  SMTP_FROMADDRESS ;
    $headers['Reply-to'] = SMTP_FROMADDRESS;
    $mail = new exponentMail();
    $mail->addTo($emails);
    $mail->subject("Chi tiết đặt mua hàng tại " . SITE_TITLE . " ngày " .date("d/m/Y"));
    $mail->addHTML($msg);
    $mail->addHeaders($headers);
    $mail->addFrom(SMTP_FROMADDRESS,SITE_TITLE );
    // Send the message
    $mail->send();
    //
    
		$template->output();
}
?>
